package com.dream.testtubebaby.fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dream.testtubebaby.R;
import com.dream.testtubebaby.activity.LoginActivity;
import com.dream.testtubebaby.activity.MainActivity;
import com.dream.testtubebaby.activity.MyAttentionListActivity;
import com.dream.testtubebaby.activity.SelectPhotoActivity;
import com.dream.testtubebaby.activity.UserInfoActivity;
import com.dream.testtubebaby.data.user.User;
import com.dream.testtubebaby.data.user.UserDataManager;
import com.dream.testtubebaby.net.ServerStub;
import com.dream.testtubebaby.okhttp.OkHttpClientManager;
import com.dream.testtubebaby.okhttp.OkHttpClientManager.Param;
import com.dream.testtubebaby.utils.ImageLoader;
import com.dream.testtubebaby.utils.SharePreferencesManager;
import com.dream.testtubebaby.utils.ShareSDKUtils;
import com.dream.testtubebaby.utils.ToastUtil;
import com.dream.testtubebaby.utils.VersionConfig;
import com.mob.tools.utils.UIHandler;
import com.squareup.okhttp.Request;

@SuppressWarnings("deprecation")
public class AccountFragment extends Fragment implements OnClickListener,
		Callback {
	private View rootView;
	private TextView account_status_tv;
	private TextView account_name_tv;
	private SharePreferencesManager mSharePreferencesManager;
	private ImageView select_photo;
	private ImageView share_app_img;
	private String app_image_path;
	private RelativeLayout logoutRl;
	private ProgressDialog mProgressDialog;
	private SharePreferencesManager mPreferencesManager;
	private int notify_flag;
	private String language_code;
	private int language_index = 0;
	private String[] select_language;
	private String[] select_code;
	private boolean restart_activity_flag = false;
	
	private ProgressDialog softwareUpdateProgressDialog;
	private Handler downloadDoneHandler = new Handler();
	private int newVerCode = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (rootView == null) {
			rootView = inflater.inflate(R.layout.fragment_more, null);
			initView(rootView);
			initOtherView(rootView);
			initProgressDialog();
			mPreferencesManager = new SharePreferencesManager(getActivity());
			select_language = getResources().getStringArray(R.array.language_select);
			select_code = getResources().getStringArray(R.array.language_code_select);
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}

		return rootView;
	}

	private void initOtherView(View view) {
		RelativeLayout my_Attention = (RelativeLayout) view
				.findViewById(R.id.my_Attention);
		my_Attention.setOnClickListener(this);
		RelativeLayout notification_setting = (RelativeLayout) view
				.findViewById(R.id.notification_setting);
		notification_setting.setOnClickListener(this);
		RelativeLayout language_setting = (RelativeLayout)view.findViewById(R.id.language_setting);
		language_setting.setOnClickListener(this);
	}

	private void initView(View view) {
		mSharePreferencesManager = new SharePreferencesManager(getActivity());
		RelativeLayout mMyAccountLayout = (RelativeLayout) view
				.findViewById(R.id.my_account_layout);
		mMyAccountLayout.setOnClickListener(this);
		RelativeLayout mappUpdateLayout = (RelativeLayout) view
				.findViewById(R.id.app_update);
		mappUpdateLayout.setOnClickListener(this);
		account_status_tv = (TextView) view
				.findViewById(R.id.account_login_state_tv);
		account_name_tv = (TextView) view.findViewById(R.id.account_name_tv);
		if (mSharePreferencesManager.readUserId() != 0) {
			account_name_tv.setText(mSharePreferencesManager.readUserName());
			account_status_tv.setText(R.string.user_login_status_yes);
		}
		select_photo = (ImageView) view.findViewById(R.id.select_photo_img);
		select_photo.setOnClickListener(this);

		File file = new File(Environment.getExternalStorageDirectory()
				+ SelectPhotoActivity.USER_PHOTO_DIR
				+ SelectPhotoActivity.USER_PHOTO_FILE_NAME);
		if(file.exists()){
			ImageLoader.getInstance().loadImage(
					Environment.getExternalStorageDirectory()
							+ SelectPhotoActivity.USER_PHOTO_DIR
							+ SelectPhotoActivity.USER_PHOTO_FILE_NAME,
					select_photo);
		}else{
			String photo_url = mSharePreferencesManager.readPhotoUrl();
			if(!TextUtils.isEmpty(photo_url)){
				String []urls = photo_url.split(",");
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append("http://");
				stringBuilder.append(urls[0]);
				ImageLoader.getInstance().loadNetWorkImage(stringBuilder.toString(), select_photo);
			}
		}

		logoutRl = (RelativeLayout) view.findViewById(R.id.app_logout);
		logoutRl.setOnClickListener(this);

		share_app_img = (ImageView) view
				.findViewById(R.id.share_app_img);
	}

	private void initProgressDialog() {
		mProgressDialog = new ProgressDialog(getActivity());
		mProgressDialog.setMessage(getResources().getString(
				R.string.bbs_uploadfile_msg));
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new Thread() {
			public void run() {
				initImagePath();
				UIHandler.sendEmptyMessageDelayed(1, 100, AccountFragment.this);
			}
		}.start();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.select_photo_img: {
			Intent intent = new Intent(getActivity(), SelectPhotoActivity.class);
			startActivityForResult(intent,
					SelectPhotoActivity.REQUEST_PICTURE_CODE);
			getActivity().overridePendingTransition(R.anim.sub_enter,
					R.anim.main_exit);
		}
			break;
		case R.id.my_account_layout: {
			Intent intent = new Intent(getActivity(), UserInfoActivity.class);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.sub_enter,
					R.anim.main_exit);
		}
			break;
		case R.id.app_update:
			handleSoftwareVersionUpdate();
			break;
		case R.id.my_Attention:
			startMyAttention();
			break;
		case R.id.app_aboutme:
			break;
		case R.id.app_logout:
			doLogout();
			break;
		case R.id.notification_setting:
			showNotifyDialog();
			break;
		case R.id.language_setting:
			showLanguageSelectDialog();
			break;
		case R.id.share_app_img:
			ShareSDKUtils.showShare(getActivity(),app_image_path);
			break;
		default:
			break;
		}
	}

	private void initImagePath() {
		try {
			String cachePath = com.mob.tools.utils.R.getCachePath(
					getActivity(), null);
			app_image_path = cachePath + "share_testtubebaby_image.jpg";
			File file = new File(app_image_path);
			if (!file.exists()) {
				file.createNewFile();
				Bitmap pic = BitmapFactory.decodeResource(getResources(),
						R.drawable.ic_launcher);
				FileOutputStream fos = new FileOutputStream(file);
				pic.compress(CompressFormat.JPEG, 100, fos);
				fos.flush();
				fos.close();
			}
		} catch (Throwable t) {
			t.printStackTrace();
			app_image_path = null;
		}
	}

	private void showNotifyDialog() {
		notify_flag = mPreferencesManager.readNofityFlag();
		AlertDialog.Builder builder = new Builder(getActivity());
		String[] select = getResources().getStringArray(R.array.nofity_select);
		builder.setSingleChoiceItems(select, notify_flag,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						notify_flag = which;
					}
				});
		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						mPreferencesManager.writeNofityFlag(notify_flag);
					}
				});
		builder.create().show();
	}

	private void showLanguageSelectDialog() {
		language_code = mPreferencesManager.readLanguageCode();
		AlertDialog.Builder builder = new Builder(getActivity());
		for (int i = 0; i < select_code.length; i++) {
			if(select_code[i].equals(language_code)){
				language_index = i;
				break;
			}
		}
		builder.setSingleChoiceItems(select_language, language_index,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						language_index = which;
						if(!language_code.equals(select_code[language_index])){
							language_code = select_code[language_index];
							restart_activity_flag = true;
						}
					}
				});
		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(restart_activity_flag){
							mPreferencesManager.switchLanguage(language_code);
							getActivity().finish();
							Intent it = new Intent(getActivity(), MainActivity.class);
						    startActivity(it);
						}
					}
				});
		builder.create().show();
	}
	
	private void startMyAttention() {
		Intent intent = new Intent(getActivity(), MyAttentionListActivity.class);
		startActivity(intent);
	}

	private void doLogout() {
		new AlertDialog.Builder(getActivity())
				.setMessage(getString(R.string.quit_tip))
				.setNeutralButton(getString(android.R.string.ok),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								mSharePreferencesManager.cleanOffUserInfo();
								Intent intent = new Intent(getActivity(),
										LoginActivity.class);
								getActivity().startActivity(intent);
								getActivity().finish();
							}
						})
				.setNegativeButton(getString(android.R.string.cancel),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (data != null && requestCode == LoginActivity.REQUEST_LOGIN) {
				ToastUtil.toast(getActivity(), R.string.user_login_sucess);
				User user = (User) data
						.getSerializableExtra(UserDataManager.USER_KEY);
				account_status_tv.setText(R.string.user_login_status_yes);
				account_name_tv.setText(user.getName());
			} else if (requestCode == SelectPhotoActivity.REQUEST_PICTURE_CODE) {
				Bitmap bitmap = data
						.getParcelableExtra(SelectPhotoActivity.GET_PICTURE_KEY);
				select_photo.setImageBitmap(bitmap);
				uploadPhotofile();
			}
		}
	}

	private void uploadPhotofile() {
		mProgressDialog.show();
		File file = new File(Environment.getExternalStorageDirectory()
				+ SelectPhotoActivity.USER_PHOTO_DIR
				+ SelectPhotoActivity.USER_PHOTO_FILE_NAME);
		String fileKey = "1";
		Param[] params = new Param[2];
		params[0] = new OkHttpClientManager.Param("uid",
				String.valueOf(mPreferencesManager.readUserId()));
		params[1] = new OkHttpClientManager.Param("type", "1");
		try {
			OkHttpClientManager.postAsyn(ServerStub.BASEURL
					+ "m=Home&c=App&a=uploadfile",
					new OkHttpClientManager.ResultCallback<String>() {

						@Override
						public void onError(Request request, Exception e) {
							ToastUtil.toast(getActivity(), e.toString());
							mProgressDialog.dismiss();
						}

						@Override
						public void onResponse(String response) {
							mProgressDialog.dismiss();
//							mSharePreferencesManager.writePhotoUrl(name);
							if ("200".equals(response)) {
								ToastUtil.toast(getActivity(),
										R.string.bbs_uploadfile_success);
							}

						}
					}, file, fileKey, params);
		} catch (IOException e) {
			e.printStackTrace();
			mProgressDialog.dismiss();
		}
	}

	private void handleSoftwareVersionUpdate() {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
				.build());
		if (getServerVerCode()) {
			int vercode = VersionConfig.getVerCode(getActivity());
			if (newVerCode > vercode) {
				doNewVersionUpdate();
			} else {
				notNewVersionShow();
			}
		}
	}

	private boolean getServerVerCode() {
		try {
			String verjson = ServerStub
					.getSoftwareVersionContent(VersionConfig.UPDATE_SERVER
							+ VersionConfig.UPDATE_VERJSON);
			JSONArray array = new JSONArray(verjson);
			if (array.length() > 0) {
				JSONObject obj = array.getJSONObject(0);
				try {
					newVerCode = Integer.parseInt(obj.getString("verCode"));
				} catch (Exception e) {
					newVerCode = -1;
					return false;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private void notNewVersionShow() {
		int verCode = VersionConfig.getVerCode(getActivity());
		String verName = VersionConfig.getVerName(getActivity());
		StringBuffer sb = new StringBuffer();
		// sb.append(getActivity().getResources().getString(
		// R.string.current_version_text));
		// sb.append(verName);
		// sb.append("   Code:");
		// sb.append(verCode);
		// sb.append("\n"
		// + getActivity().getResources().getString(
		// R.string.current_version_newest_text));
		sb.append(getActivity().getResources().getString(
				R.string.current_version_newest_text));
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle(
						getActivity().getResources().getString(
								R.string.software_update_text))
				.setMessage(sb.toString())
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}

						}).create();
		dialog.show();
	}

	protected void doNewVersionUpdate() {
		softwareUpdateProgressDialog = new ProgressDialog(getActivity());
		softwareUpdateProgressDialog.setTitle(getActivity().getResources()
				.getString(R.string.software_update_text));
		softwareUpdateProgressDialog.setMessage(getActivity().getResources()
				.getString(R.string.down_load_text));
		softwareUpdateProgressDialog
				.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		downloadAppFile(VersionConfig.UPDATE_SERVER
				+ VersionConfig.UPDATE_APKNAME);
	}

	protected void downloadAppFile(final String url) {
		softwareUpdateProgressDialog.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is == null) {
						throw new RuntimeException("isStream is null");
					}
					File file = new File(
							Environment.getExternalStorageDirectory(),
							VersionConfig.UPDATE_SAVENAME);
					fileOutputStream = new FileOutputStream(file);
					byte[] buf = new byte[1024];
					int ch = -1;
					do {
						ch = is.read(buf);
						if (ch <= 0)
							break;
						fileOutputStream.write(buf, 0, ch);
					} while (true);
					is.close();
					fileOutputStream.close();
					DownLoadDone();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	protected void DownLoadDone() {
		downloadDoneHandler.post(new Runnable() {
			public void run() {
				softwareUpdateProgressDialog.cancel();
				Dialog installDialog = new AlertDialog.Builder(getActivity())
						.setTitle(
								getActivity().getResources().getString(
										R.string.down_load_complete_text))
						.setMessage(
								getActivity().getResources().getString(
										R.string.advance_to_install_text))
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										installNewApk();
										getActivity().finish();
									}
								})
						.setNegativeButton(android.R.string.cancel,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								}).create();
				installDialog.show();
			}
		});
	}

	protected void installNewApk() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(
				Uri.fromFile(new File(
						Environment.getExternalStorageDirectory(),
						VersionConfig.UPDATE_SAVENAME)),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case 1: {
			share_app_img.setOnClickListener(this);
		}
			break;
		}
		return false;
	}
}